package com.ebring.shareEducation.controller;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.ebring.shareEducation.bean.User;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.io.FilenameUtils;
import org.json.JSONObject;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.multipart.MultipartFile;

/**
 * Ajax异步上传图片
 *
 * @author Hang.W
 * @version 1.0, 2017-02-14 00:51:39
 */
@Controller
@CrossOrigin(origins = "http://wangliang.vipgz1.idcfengye.com", maxAge = 3600)
@Api(value = "Ajax异步上传图片" ,tags = {"Ajax异步上传图片"})
public class UploadController {

    public static HashMap<String,HttpSession> sessionMap = new HashMap<String,HttpSession>();
    /**
     * 使用Ajax异步上传图片
     *
     * @param pic 封装图片对象
     * @param request
     * @param response
     * @throws IOException
     * @throws IllegalStateException
     */
    // @RequestMapping("/upload/uploadPic.do")
//    @RequestMapping(value = "/upload/uploadPic", method = RequestMethod.POST,consumes = "application/json")
    @PostMapping("/upload/uploadPic")
    @ApiOperation(value="使用Ajax异步上传图片", notes="使用Ajax异步上传图片")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType="query",name = "MultipartFile", value = "图片文件", required = true, dataType = "String"),
    })
    public void uploadPic(MultipartFile pic, HttpServletRequest request, HttpServletResponse response) throws IllegalStateException, IOException {

        try {
            User user;
            HttpSession session;
            if (null != sessionMap.get("zhangsheng")){
                session= sessionMap.get("zhangsheng");
            }else {
                session = request.getSession();
                sessionMap.put("zhangsheng",session);
            }

            if (null !=session.getAttribute("user")) {
                user=(User)session.getAttribute("user");
            }else {
                user= new User();
                user.setUsername("1234");
                session.setAttribute("user",user);
            }

            //自己把SessionID保存在cookie中



            System.out.println(user.getUsername());
            // 获取图片原始文件名
            String originalFilename = pic.getOriginalFilename();
            System.out.println(originalFilename);

            // 文件名使用当前时间
            String name = new SimpleDateFormat("yyyyMMddHHmmssSSS").format(new Date());

            // 获取上传图片的扩展名(jpg/png/...)
            String extension = FilenameUtils.getExtension(originalFilename);

            // 图片上传的相对路径（因为相对路径放到页面上就可以显示图片）
//            String path = "\\upload\\" + name + "." + extension;
            String path = "\\upload\\" +originalFilename;

            // 图片上传的绝对路径
//            String url = request.getSession().getServletContext().getRealPath("") + path;
            String url= "e:"+path;
            File dir = new File(url);
            if(!dir.exists()) {
                dir.mkdirs();
            }

            // 上传图片
            pic.transferTo(new File(url));

            // 将相对路径写回（json格式）
            JSONObject jsonObject = new JSONObject();
            // 将图片上传到本地
            jsonObject.put("path", url);

            // 设置响应数据的类型json
            response.setContentType("application/json; charset=utf-8");
            // 写回
            response.getWriter().write(jsonObject.toString());

        } catch (Exception e) {
            throw new RuntimeException("服务器繁忙，上传图片失败");
        }
    }

}